import shell from 'shelljs'
import env from './env.js'
import fs from 'fs'
import { fileURLToPath } from 'node:url'
import { dirname,resolve } from 'node:path'
const __dirname = dirname(fileURLToPath(import.meta.url))
const versionBuffer = fs.readFileSync(resolve(__dirname, './publish/.version'))
import Version,{ versionControl } from'./publish/version.js'
const version = versionBuffer.toString().replace(new RegExp('\n'), '')
const a = version.split('.')[0]
const b = version.split('.')[1]
const c = version.split('.')[2]
const version1 = new Version(a, b, c)
versionControl.addVersion(version1)
versionControl.getVersion(0).increment('patch')
const newVersion = versionControl.getVersion(0).toString()
fs.writeFileSync(resolve(__dirname, './publish/.version'), versionControl.getVersion(0).toString())
const execFn = (serviceOutput) => {
  shell.exec(`
  tar cvzf ${env.dir}.tar.gz ${env.dir}/
  ssh ${env.ssh} '
    rm -rf ${serviceOutput}${env.dir}
    mkdir -p ${serviceOutput}${env.dir}
  '
  scp -r ${env.dir}.tar.gz ${env.ssh}:${serviceOutput}
  ssh ${env.ssh} '
    cd ${serviceOutput}
    tar cvzf ${env.dir}-${newVersion}.tar.gz ${env.dir}/
    rm -rf ${serviceOutput}${env.dir}
    tar -zxvf ${serviceOutput}${env.dir}.tar.gz
  '
  rm -rf ${env.dir}.tar.gz
  clear
  git pull
  git commit -m '代码发布-'${+new Date()}
  git push
  `)
}

const serviceOutputList = env.serviceOutputList;
serviceOutputList.forEach((item)=>{
  execFn(item)
})
